<template>
    <TopNav />
    <div class="wrap">
        <div class="left">
            <div class="left_container">
                <div class="top">
                    <div class="order_number">
                        <span class="label"><el-tag type="primary">单号</el-tag></span>
                        <span class="content">{{ row?.checkNumber }}</span>
                    </div>
                    <div class="goods">
                        <div>{{ currentSelectGoods?.goodsName }} </div>

                        <el-button type="primary" class="check_equal" v-if="currentSelectGoods">盘平</el-button>
                    </div>
                    <div class="infos">
                        <div>
                            <span class="label"><el-tag type="success">盘</el-tag></span>
                            <span>12312</span>
                        </div>
                        <div>
                            <span class="label"><el-tag type="primary">库</el-tag></span>
                            <span>{{ currentSelectGoods?.inventoryQuantity }}</span>
                        </div>
                    </div>
                    <div class="btns">
                        <el-button type="danger" size="large">删除</el-button>
                        <el-button type="primary" size="large">上页</el-button>
                        <el-button type="primary" size="large">下页</el-button>
                    </div>
                </div>
                <div class="table_wrap">
                    <!-- :header-cell-style="{ backgroundColor: 'var(--ev-c-black)', color: '#fff' }"  :header-cell-style="{ backgroundColor: 'var(--el-color-primary)', color: '#fff' }"-->
                    <el-table :show-summary="true" sum-text="合计" :summary-method="getSummaries" stripe :data="tableData"
                        ref="singleTableRef" @current-change="handleCurrentChange" highlight-current-row
                        class-name="my_table">
                        <el-table-column type="index" width="60" />

                        <el-table-column prop="num" label="数/重量" />

                    </el-table>
                </div>
                <div class="bottom">
                    <el-button type="warning" size="large">重盘</el-button>
                    <el-button type="success" size="large">保存</el-button>
                    <el-button type="primary" size="large">提交</el-button>
                </div>
            </div>
        </div>
        <div class="right">
            <div class="right_top">
                <MyInput @click="showSearchKeyboard" placeholder="请输入商品首字母搜索" :innerText="goodsSearchKeywords"
                    class="item" style="width: 100%;" />

                <!-- <el-input :prefix-icon="Search" @click="showSearchKeyboard" v-model="goodsSearchKeywords"
                        size="large" placeholder="搜索商品" class="item" /> -->
                <!-- {{ netWeight }} -->

                <div class="net_weight item"><span>净重/kg：</span><span class="num">{{ weight }}</span></div>
                <div class="tare_weight item"><span>皮重/kg：</span><span class="num">{{ tareWeight }}</span></div>
                <!-- <div class="btns">
                        <el-button type="primary" size="large" @click="confirmWeight">确定</el-button>
                        <el-button type="success" size="large" style="margin-left: 5px;" @click="inputNum">输入</el-button>
                    </div> -->
            </div>
            <div class="goods_group">
                <div class="first_group">
                    <template v-if="firstGroup.length <= 7">

                        <el-button @click="chooseFirstGroup(item, index)"
                            :type="currentFirstGroupIndex == index ? 'primary' : 'default'"
                            v-for="(item, index) in firstGroup" :key="index" size="large">{{
                            item.goodsGroupName_K
                        }}</el-button>
                    </template>
                    <template v-else>
                        <el-button @click="chooseFirstGroup(item, index)"
                            :type="currentFirstGroupIndex == index ? 'primary' : 'default'"
                            v-for="(item, index) in firstGroup.slice(0, 6)" :key="index" size="large">{{
                            item.goodsGroupName_K }}</el-button>

                        <el-popover placement="bottom" :width="1000" trigger="click"
                            :visible="firstGroupPopoverVisible">
                            <template #reference>
                                <el-button size="large" icon="ArrowDownBold"
                                    @click="firstGroupPopoverVisible = !firstGroupPopoverVisible">更多</el-button>
                            </template>
                            <div class="more_btns">
                                <el-button @click="chooseFirstGroup(item, index)"
                                    :type="currentFirstGroupIndex == index ? 'primary' : 'default'"
                                    v-for="(item, index) in firstGroup" :key="index" size="large">{{
                            item.goodsGroupName_K }}</el-button>
                            </div>

                        </el-popover>

                    </template>

                </div>
                <div class="second_group">
                    <template v-if="secondGroup.length <= 7">
                        <el-button @click="chooseSecondGroup(item, index)"
                            :type="currentSecondGroupIndex == index ? 'primary' : 'default'"
                            v-for="(item, index) in secondGroup" :key="index" size="large">{{
                            item.goodsGroupName_K
                        }}</el-button>
                    </template>
                    <template v-else>
                        <el-button @click="chooseSecondGroup(item, index)"
                            :type="currentSecondGroupIndex == index ? 'primary' : 'default'"
                            v-for="(item, index) in secondGroup.slice(0, 6)" :key="index" size="large">{{
                            item.goodsGroupName_K }}</el-button>

                        <el-popover placement="bottom" :width="1000" trigger="click"
                            :visible="secondGroupPopoverVisible">
                            <template #reference>
                                <el-button size="large" icon="ArrowDownBold"
                                    @click="secondGroupPopoverVisible = !secondGroupPopoverVisible">更多</el-button>
                            </template>
                            <div class="more_btns">
                                <el-button @click="chooseSecondGroup(item, index)"
                                    :type="currentSecondGroupIndex == index ? 'primary' : 'default'"
                                    v-for="(item, index) in secondGroup" :key="index" size="large">{{
                            item.goodsGroupName_K }}</el-button>
                            </div>

                        </el-popover>

                    </template>

                </div>
            </div>
            <div class="goods_list" ref="goodsListWrapRef" v-if="currentPageData.length > 0">

                <div v-for="(item, index) in currentPageData" class="item"
                    :class="{ active: currentSelectGoods?.goodsID === item.goodsID }" @click="selectGoods(item)">
                    <div class="goods_name">{{ item.goodsName }}</div>
                    <div class="info">
                        <div><span>{{ item.checkQuantity }}</span><span class="item1">盘</span></div>
                        <div><span>{{ item.inventoryQuantity }}</span><span class="item2">库</span></div>
                        <div><span :class="item.proFitLossQuantity >= 0 ? 'green' : 'red'">{{ item.proFitLossQuantity
                                }}</span><span class="item3">盈</span></div>
                    </div>
                </div>

                <el-button v-if="currentPageNo > 1" @click="currentPageNo--" style="height: 100%;">上一页</el-button>
                <el-button type="primary" v-if="currentPageNo < totalPages" @click="currentPageNo++"
                    style="height: 100%;margin-left: 0;">下一页</el-button>

            </div>
            <div class="empty" v-else>
                <el-empty description="未搜索到商品，请更换关键字或选择其它分组" />
            </div>
        </div>
        <!--搜索键盘-->
        <SearchKeyboard v-model="isShowSearchKeyboard" keyboardContainerClass="newcheck_goods_class"
            @onChange="onSearchKeyboardChange"></SearchKeyboard>

        <!--当前选中商品弹窗-->
        <el-dialog v-model="goodsDialogVisible" class="goods_dialog" :title="`${currentSelectGoods?.goodsName}`" width="800">
            {{ currentSelectGoods }}
            <el-descriptions size="large" title="">
            <el-descriptions-item label="库存">{{ currentSelectGoods.inventoryQuantity }}</el-descriptions-item>
            
        </el-descriptions>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="orderDescDialogVisible = false">
                        取消
                    </el-button>
                    <el-button size="large" type="primary" @click="orderDescDialogVisible = false">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>


<script setup lang="ts">

//@ts-nocheck
import SearchKeyboard from '@renderer/components/SearchKeyboard.vue'
import NP from 'number-precision'
import pinyin from "pinyin";
import { ElMessage } from 'element-plus'
import { getFirstGroup, getSecondGroup, getCheckDetails } from '@renderer/api/newcheck'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@renderer/store/user'
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted, computed, h } from 'vue'
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const { userInfo, shopInfo } = storeToRefs(userStore)
const shopID = shopInfo.value.shopID
const saleOrganizationID = userInfo.value.user_organizationId
const row = ref() //上一页传过来的row
const isShowSearchKeyboard = ref(false)
const goodsDialogVisible = ref(false)
const tableData = ref([
    {
        num: 10,
    }, {
        num: 13
    }
])
const currentSelectGoods = ref(null)
const goodsSearchKeywords = ref('') //搜索关键字
const currentPageNo = ref(1) //当前页
const pageSize = ref(30)  //分页页码
const firstGroup = ref([])

const hasLoadedFirstGroupGoodsData = ref({}) //已经加载过的一级分组全部商品 {"一级分组group_ID_K":[]...}
const hasLoadedFirstGroupAndSecondGroup = ref({}) //已经加载过的一级分组下的二级分组 {"一级分组group_ID_K":[二级分组]...}
const firstGroupPopoverVisible = ref(false)
const secondGroupPopoverVisible = ref(false)
const currentFirstGroupIndex = ref(0) //一级分组选中索引
const secondGroup = ref([])
const currentSecondGroupIndex = ref(0)//二级分组选中索引
const currentFirstGroupGoodsList = ref([]) //当前一级分组下的全部商品
const currentSecondGroupGoodsList = computed(() => { //当前选中的一级、二级分组的数据
    if (currentSecondGroupIndex.value == 0) {
        return currentFirstGroupGoodsList.value
    } else {
        console.log(currentFirstGroupGoodsList.value)
        return currentFirstGroupGoodsList.value.filter(item => item.groupID_K == secondGroup.value[currentSecondGroupIndex.value].goodsGroupID_K)
    }

})
console.log(1)
// onMounted(async()=>{


// })


//是否选择商品
const isSelectGoods = computed(() => {
    return currentSelectGoods.value !== null
})

onMounted(async () => {
    //读取上页行数据
    row.value = JSON.parse(route.query.row)
    console.log(row.value.checkNumber)
    //一级分组
    await getFirstGroupData()

    // // //二级分组
    await getSecondGroupData()

    // // //查询一级分组下的全部商品
    await getCheckDetailsData()

})

async function getFirstGroupData() {
    const { data } = await getFirstGroup(saleOrganizationID, shopID, row.value.checkTemplateID)
    firstGroup.value = data.concat({ goodsGroupName_K: '新加1' }, { goodsGroupName_K: '新新加2新加2新加2新加2加2' }, { goodsGroupName_K: '新加3' })

}

async function getSecondGroupData() {
    const firstGoodsGroupID = firstGroup.value.find((item, index) => index == currentFirstGroupIndex.value).goodsGroupID_K
    if (!hasLoadedFirstGroupAndSecondGroup.value[firstGoodsGroupID]) {
        const { data } = await getSecondGroup(saleOrganizationID, shopID, row.value.checkTemplateID, firstGoodsGroupID)
        data.unshift({
            goodsGroupID_K: '',
            goodsGroupName_K: '全部'
        })
        secondGroup.value = data
        hasLoadedFirstGroupAndSecondGroup.value[firstGoodsGroupID] = data
    } else {
        secondGroup.value = hasLoadedFirstGroupAndSecondGroup.value[firstGoodsGroupID]
    }

}
async function getCheckDetailsData() {
    const groupID_k = firstGroup.value[currentFirstGroupIndex.value].goodsGroupID_K
    if (!hasLoadedFirstGroupGoodsData.value[groupID_k]) {
        const { data } = await getCheckDetails(saleOrganizationID, shopID, row.value.checkTemplateID, groupID_k, row.value.id)
        currentFirstGroupGoodsList.value = data
        hasLoadedFirstGroupGoodsData.value[groupID_k] = data
    } else {
        currentFirstGroupGoodsList.value = hasLoadedFirstGroupGoodsData.value[groupID_k]
    }


}


async function chooseFirstGroup(item, index) {

    currentFirstGroupIndex.value = index
    currentPageNo.value = 1

    //选中全部
    currentSecondGroupIndex.value = 0
    //  if (!hasLoadedFirstGroupGoodsData.value[item.goodsGroupID_K]) { //未加载过 
    //根据1级分组查询数据
    await getCheckDetailsData()
    //查询二级分组数据
    await getSecondGroupData()
    //     hasLoadedFirstGroupGoodsData.value[item.goodsGroupID_K] = currentFirstGroupGoodsList.value

    // } else {
    //     currentFirstGroupGoodsList.value = hasLoadedFirstGroupGoodsData.value[item.goodsGroupID_K]
    // }

    firstGroupPopoverVisible.value = false
}

async function chooseSecondGroup(item, index) {
    currentSecondGroupIndex.value = index
    currentPageNo.value = 1
    secondGroupPopoverVisible.value = false
}

const totalPages = computed(() => {
    return Math.ceil((currentSecondGroupGoodsList.value
        .filter(item => {
            const pinyinItem = pinyin(item.goodsName, {
                style: pinyin.STYLE_FIRST_LETTER //首字母模式
            }).join('')
            return pinyinItem.indexOf(goodsSearchKeywords.value) != -1
        }).length - (pageSize.value - 1)) / (pageSize.value - 2)) + 1;
})
//当前页数据
const currentPageData = computed(() => {
    let items = currentSecondGroupGoodsList.value.filter(item => {
        const pinyinItem = pinyin(item.goodsName, {
            style: pinyin.STYLE_FIRST_LETTER //首字母模式
        }).join('')
        //console.log(pinyinItem)
        return pinyinItem.indexOf(goodsSearchKeywords.value) != -1
    })
    // console.log(items)
    const itemsPerPageFirstPage = pageSize.value - 1
    const itemsPerPageOtherPages = pageSize.value - 2

    let start, end;
    if (currentPageNo.value === 1) {
        start = 0;
        end = itemsPerPageFirstPage;
    } else if (currentPageNo.value === totalPages.value) {
        start = itemsPerPageFirstPage + (totalPages.value - 2) * itemsPerPageOtherPages;
        end = items.length;
    } else {
        start = itemsPerPageFirstPage + (currentPageNo.value - 2) * itemsPerPageOtherPages;
        end = start + itemsPerPageOtherPages;

    }

    // 分割商品列表
    const paginatedItems = items.slice(start, end);
    return paginatedItems
})

//选择商品
function selectGoods(item, index) {
    currentSelectGoods.value = item
    goodsDialogVisible.value = true
}

//表格合计
function getSummaries({ columns, data }) {
    console.log(columns)
    console.log(data)
    const sums = data.reduce((prev, currentVal) => {
        return NP.plus(prev, currentVal.num)
    }, 0)
    // return [h('div', { style: { textDecoration: 'underline' } }, [
    //     '合计',
    //   ]),123]
    return [h('div', {}, [
        '合计',
    ]), sums]
}
//搜索商品
function onSearchKeyboardChange(val) {
    console.log('val:' + val)
    goodsSearchKeywords.value = val
}

function showSearchKeyboard() {
    console.log('focus!')
    isShowSearchKeyboard.value = true
    console.log(isShowSearchKeyboard)
}

//输入
function inputNum() {
    if (!isSelectGoods.value) {
        ElMessage({
            message: '请先选择商品',
            type: 'warning',
        })
        return
    }

}

//确定重量
function confirmWeight() {
    if (!isSelectGoods.value) {
        ElMessage({
            message: '请先选择商品',
            type: 'warning',
        })
        return
    }
}
</script>

<style scoped lang='scss'>
.nav_right {
    display: flex;
    align-items: center;


}

.wrap {
    display: flex;
    height: calc(100% - 50px);
    box-sizing: border-box;
    background-color: var(--ev-c-white);
    overflow: hidden;

    .left {
        width: 30%;
        box-sizing: border-box;
        padding-left: 5px;

        .left_container {
            height: 100%;
            box-sizing: border-box;
            position: relative;

            .top {

                .order_number {
                    display: flex;
                    line-height: 40px;
                    height: 40px;
                    background-color: var(--el-color-primary-light-7);
                    margin-bottom: 5px;
                    padding-left: 5px;

                    .label {
                        width: 40px;
                    }

                    .content {
                        text-align: center;
                        flex: 1;
                    }
                }

                .goods {
                    text-align: center;
                    line-height: 40px;
                    height: 40px;
                    background-color: var(--el-color-primary-light-7);
                    margin-bottom: 5px;
                    display: flex;
                    align-items: center;

                    &>div {
                        flex: 1;
                    }

                    .check_equal {
                        width: 60px;
                    }
                }

                .infos {
                    display: flex;
                    align-items: center;
                    background-color: var(--el-color-primary-light-7);
                    margin-bottom: 5px;
                    padding-left: 5px;

                    height: 40px;

                    &>div {
                        flex: 1;
                        display: flex;
                        align-items: center;

                        .label {
                            margin-right: 10px;
                        }
                    }
                }

                .btns {
                    display: flex;
                    margin-bottom: 5px;

                    :deep(.el-button) {
                        flex: 1;
                    }
                }
            }


            .table_wrap {

                margin-bottom: 10px;
                height: calc(100% - 95px - 101px - 40px - 10px);
                border: 1px solid var(--el-border-color);
                border-bottom: 0;
                box-sizing: border-box;
                width: 100%;

                .my_table {
                    width: 100%;
                    height: 100%;
                }


            }

            .bottom {
                display: flex;

                :deep(.el-button) {
                    flex: 1;
                }
            }




        }

    }

    .right {
        width: calc(70% - 5px);
        padding: 5px 0 0 5px;

        box-sizing: border-box;

        .right_top {
            display: grid;
            // align-items: center;
            margin-bottom: 5px;
            grid-template-columns: 2fr 2fr 2fr 1fr;
            gap: 5px;

            .btns {
                display: flex;

                :deep(.el-button) {
                    flex: 1;
                }
            }

            .item {
                line-height: 40px;
                height: 40px;

                span {
                    font-size: 20px;
                }

                .num {
                    color: var(--el-color-danger);

                }
            }
        }

        .goods_group {

            .first_group,
            .second_group {
                display: grid;
                gap: 5px;
                grid-template-rows: 1fr;
                grid-template-columns: repeat(7, minmax(90px, 1fr));
                margin-bottom: 5px;

            }

            .group_name {
                color: #000;
                font-size: 16px;
            }

            .active {
                color: #fff;
            }

            :deep(.el-button) {
                // border-radius: 0;
                // border: none;
                padding: 2px;
                white-space: break-spaces;

                span {
                    display: -webkit-box !important;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                    overflow: hidden;
                }

            }

            :deep(.el-button+.el-button) {
                margin-left: 0;

            }
        }

        .goods_list {
            height: calc(100% - 50px - 90px);
            padding: 2px;
            overflow: hidden;
            box-sizing: border-box;
            display: grid;
            gap: 2px;
            grid-template-rows: repeat(6, 1fr);
            grid-template-columns: repeat(5, 1fr);
            background-color: var(--el-color-primary);

            .item {
                // text-indent: 5px;
                background-color: var(--ev-c-white);
                box-sizing: border-box;
                // border: 1px solid #ccc;
                // border-radius: 2px;
                padding: 5px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                &.active {
                    background-color: var(--el-color-primary-light-7);

                }

                .goods_name {
                    display: -webkit-box;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 5;
                    overflow: hidden;
                    flex: 1;

                }

                .info {
                    flex: 1;
                    font-size: 14px;
                    text-align: right;
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;

                    span {
                        display: inline-block;

                        &.green {
                            color: var(--el-color-success);
                        }

                        &.red {
                            color: var(--el-color-danger);
                        }
                    }

                    .item1 {
                        color: var(--el-color-primary);
                        margin-left: 8px;
                    }

                    .item2 {
                        margin-left: 8px;
                    }

                    .item3 {
                        color: var(--el-color-info);
                        margin-left: 8px;
                    }
                }
            }

        }

        .empty {
            height: calc(100% - 50px - 90px);
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}

.more_btns {
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    :deep(.el-button) {
        margin: 0 0 10px 10px;
    }

    :deep(.el-button+.el-button) {
        margin: 0 0 10px 10px;


    }
}
</style>